package com.zqq.framedagger.ui.activity

import android.os.Bundle
import android.support.v4.app.Fragment
import com.ashokvarma.bottomnavigation.BottomNavigationBar
import com.eightbitlab.rxbus.Bus
import com.eightbitlab.rxbus.registerInBus
import com.zqq.baselibrary.common.AppManager
import com.zqq.baselibrary.ui.activity.BaseActivity
import com.zqq.baselibrary.utils.AppPrefsUtils
import com.zqq.framedagger.R
import com.zqq.framedagger.ui.fragment.HomeFragment
import com.zqq.framedagger.ui.fragment.MeFragment
import com.zqq.goods.event.UpdateCartSizeEvent
import com.zqq.goods.ui.fragment.CartFragment
import com.zqq.goods.ui.fragment.CategoryFragment
import com.zqq.message.ui.fragment.MessageFragment
import com.zqq.provider.event.MessageBadgeEvent
import com.zqq.provider.router.RouterPath
import kotlinx.android.synthetic.main.activity_main.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.jetbrains.anko.toast
import rx.Observable
import rx.android.schedulers.AndroidSchedulers
import rx.functions.Action1
import java.util.*
import java.util.concurrent.TimeUnit

/**
 * wc
 */
class MainActivity : BaseActivity() {

    private var pressTime: Long = 0         //双击退出

    private val mStack = Stack<Fragment>()                  //Fragment 栈管理
    private val mHomeFragment by lazy { HomeFragment() }    //主界面Fragment
    private val mCategoryFragment by lazy { CategoryFragment() }    //商品分类Fragment
    private val mCartFragment by lazy { CartFragment() }    //购物车Fragment
    private val mMsgFragment by lazy { MessageFragment() }    //消息Fragment
    private val mMeFragment by lazy { MeFragment() }        //"我的"Fragment


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        initFragment()
        initBottomNav()
        changeFragment(0)
        initObserve()
        //刚进来时的显示购物车数量
        loadCartSize()
    }

    /**
     * 初始化Fragment栈管理
     */
    private fun initFragment() {
        val manager = supportFragmentManager.beginTransaction()
        manager.add(R.id.mContaier, mHomeFragment)
        manager.add(R.id.mContaier, mCategoryFragment)
        manager.add(R.id.mContaier, mCartFragment)
        manager.add(R.id.mContaier, mMsgFragment)
        manager.add(R.id.mContaier, mMeFragment)
        manager.commit()

        mStack.add(mHomeFragment)
        mStack.add(mCategoryFragment)
        mStack.add(mCartFragment)
        mStack.add(mMsgFragment)
        mStack.add(mMeFragment)
    }

    /**
     * 初始化底部导航切换事件
     */
    private fun initBottomNav() {
        mBottomNavBar.checkMsgBadge(false)  //红点
//        mBottomNavBar.checkCartBadge(10)        //个数

        //测试红点消失
//        testBottomRemove()

        mBottomNavBar.setTabSelectedListener(object : BottomNavigationBar.OnTabSelectedListener {
            override fun onTabReselected(position: Int) {
            }

            override fun onTabUnselected(position: Int) {
            }

            override fun onTabSelected(position: Int) {
                changeFragment(position)
            }
        })
    }

    //测试
    private fun testBottomRemove() {
        Observable.timer(2, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(Action1 { mBottomNavBar.checkMsgBadge(false) })

        //lambad表达式
        Observable.timer(5, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe { mBottomNavBar.checkCartBadge(0) }
    }

    /**
     * 切换Tab，切换对应的Fragment
     */
    private fun changeFragment(position: Int) {
        val manager = supportFragmentManager.beginTransaction()
        for (fragment in mStack) {
            manager.hide(fragment)
        }

        manager.show(mStack[position])
        manager.commit()
    }


    /**
     * 初始化监听，购物车数量变化及消息标签是否显示
     */
    private fun initObserve() {
        Bus.observe<UpdateCartSizeEvent>()
                .subscribe {
                    loadCartSize()
                }.registerInBus(this)

        //EventBus模式--监听自定义消息
        EventBus.getDefault().register(this)

        //监听自定义消息（JPush）
        Bus.observe<MessageBadgeEvent>()
                .subscribe { t: MessageBadgeEvent ->
                    run {
                        mBottomNavBar.checkMsgBadge(t.isVisible)
                    }
                }.registerInBus(this)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onCartSize(event: UpdateCartSizeEvent) {
        mBottomNavBar.checkCartBadge(AppPrefsUtils.getInt(RouterPath.GoodsCenter.SP_CART_SIZE))
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMsgSize(event: MessageBadgeEvent) {
        mBottomNavBar.checkMsgBadge(event.isVisible)
    }


    //加载购物车数量
    private fun loadCartSize() {
        mBottomNavBar.checkCartBadge(AppPrefsUtils.getInt(RouterPath.GoodsCenter.SP_CART_SIZE))
    }


    override fun onDestroy() {
        super.onDestroy()
        Bus.unregister(this)
        EventBus.getDefault().unregister(this)
    }


    /**
     * 重写Back事件，双击退出
     */
    override fun onBackPressed() {
        val time = System.currentTimeMillis()
        if (time - pressTime > 2000) {
            toast("再按一次退出程序")
            pressTime = time
        } else {
            AppManager.instance.exitApp(this)
        }
    }


}
